import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage'
/** components */
import { FieldManager, PreviewComponents } from './components';
import draggable from 'vuedraggable';
/** util */
import { findComponentUpward, findComponentsDownward } from '@src/util/assist';
import FormUserCenter from '@src/mform/components/FormUserCenter';
import { cloneDeep } from 'lodash'
import { getPaasBackGray } from '@src/api/LinkcApi';
import { getCompanyInfo,queryPartList, commodityList } from '@src/api/PortalApi.ts'
import { getRootWindow } from '@src/util/dom';
import { useTenantId } from '@hooks/useRootWindow.ts';
import i18n from '@src/locales'
/** 创建字段预览组件 */
export function createPreviewComp(h, field) {
  if (field.formType === 'productRegister' && this.filterFields.includes('productRegister')) {
    return null
  }
  let currFieldId = field.fieldName
  let previewComp = FieldManager.findField(field.formType);
  
  if (previewComp == null) {
    console.warn(
      `[not implement]: ${field.displayName}(${field.fieldName}): ${field.formType}. `
    );
    return null
  }
  
  // 根据字段配置创建预览内容
  if (!previewComp) return
  
  // 隐藏字段不渲染
  if (field.isHidden == 1) return
  
  let fieldPreview = h(previewComp.preview, {
    class: 'form-design__ghost',
    props: { field, setting: previewComp, disabled: true, previewMode: this.previewMode }
  });
  let disabledFormTypes = ['userCenter','shop']
  let previewClass = {
    'form-design-preview': true,
    'disabled': disabledFormTypes.includes(field.formType) || this.isOnlyPreview,
    // 被选中
    'form-design-selected': this.currField && currFieldId == this.currField.fieldName, 
    'form-design-error': field?.isError
  };
  
  const tooltipContent = `${i18n.t('common.base.delete')}${field.displayName}`;
  
  if (previewComp.isNotShowPreviewList) {
    return fieldPreview
  }
  
  return (
    <div
      class={previewClass}
      key={currFieldId}
      onClick={e => {
        e.stopPropagation();
        this.chooseField(field);
      }}
    >
      {fieldPreview}
      { (!this.isOnlyPreview) && (previewComp.forceDelete) && (
        <div class="form-design-operation">
          <div
            class="form-design-preview-delete form-design-preview-btn"
            onClick={e => {
              e.stopPropagation();
              this.deleteField(field);
            }}
          >
            <el-tooltip
              class="item"
              effect="dark"
              content={tooltipContent}
              placement="top"
            >
              <i class="iconfont icon-shanchu-copy"></i>
            </el-tooltip>
          </div>
        </div>
      )}
    </div>
  );
}

const FormPreview = {
  name: 'mform-preview',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    validate: Function,
    updateCompNumber: {
      type: Function,
      default: () => ({})
    },
    index: {
      type: Number,
      default: 1
    },
    isOnlyPreview: {
      type: Boolean,
      default: false
    },
    previewMode: {
      type: String,
      default: 'mobile'
    },
    filterFields: {
      type: Array,
      default: () => []
    },
    themeColour: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      backupValue: [],
      selectedCompNumber: [], // 被选中的控件数量
      companyInfo: {},
      grayState: false,
      partList:[],
    }
  },
  setup(){
    const { isOpenMultiLanguage } = useFormMultiLanguage();

    return {
      isOpenMultiLanguage,
    }
  },
  computed: {
    formDesignComponent() {
      return findComponentUpward(this, 'mform-design') || {};
    },
    /** 当前选中的字段 */
    currField() {
      return this.formDesignComponent?.currField || null;
    },
    /** 字段是否为空 */
    isEmpty() {
      return !Array.isArray(this.value) || this.value.length == 0;
    },
    isHasUserCenterField() {
      return this.value.some(field => field.formType == 'userCenter');
    },
    isOpenServiceMall() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.SERVICE_MALL ?? false;
    },
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler(newValue) {
        this.selectedCompNumber = [];
        newValue.forEach(item => {
          if (!this.selectedCompNumber[item.formType]) {
            this.$set(this.selectedCompNumber, item.formType, 1)
          } else {
            this.$set(this.selectedCompNumber, item.formType, this.selectedCompNumber[item.formType] + 1)
          }
        })
        this.updateCompNumber(this.selectedCompNumber);
      }
    }
  },
  mounted() {
    this.getInitData();
  },
  methods: {
    getInitData() {
      this.getCompanyInfo();
      // this.getExchangedAuth();
      if (this.isOpenServiceMall) {
        this.getMallList();
      } else {
        this.getPartList();
      }
    },
    // 获取退换货权限
    // async getExchangedAuth() {
    //   try {
    //     const { code, data } = await getPaasBackGray();
    //     if (code !== 0) return;

    //     this.grayState = data.grayState;
    //   } catch (error) {
    //     console.error('getPaasBackGray error', error);
    //   }
    // },
    // 获取公司信息
    async getCompanyInfo() {
      try {
        const { code, result } = await getCompanyInfo({});
        if (code !== 0) return;

        this.companyInfo = result;
      } catch (error) {
        console.error('getCompanyInfo error', error);
      }
    },
    /** 触发input事件 */
    emitInput(value) {
      this.$emit('input', value);
    },
    handlerIndexChanged(newIndex, oldIndex) {
      return newIndex
    },
    addEventHandler(newIndex, oldIndex) {
      let index = this.handlerIndexChanged(newIndex, oldIndex)
      let field = this.value[index];
      
      let message = this.validate && this.validate(field);
      if (message) {
        this.value.splice(index, 1);
        return this.$platform.alert(message);
      }
      
      this.$nextTick(() => {
        this.chooseField(field);
      });
      
      if (this.isHasUserCenterField && index == 0) {
        let fields = [this.value[0], this.value[1]].reverse()
        let otherFields = this.value.slice(2)
        let value = fields.concat(otherFields)
        this.formDesignComponent.emitInput(value)
        this.formDesignComponent.currField = value[1] || null
        return 
      }
      
      this.emitInput(this.value);
    },
    /** 渲染预览组件 */
    renderPreviewList(h) {
      return this.value.map(f => createPreviewComp.call(this, h, f));
    },
    /** 选中字段 */
    chooseField(field) {
      // 只展示、用户中心组件、商城组件不允许被选中
      let notChooseFields = ['userCenter','shop']
      if (this.isOnlyPreview || notChooseFields.includes(field.formType)) return;
      this.formDesignComponent.chooseField(field);
    },
    /** 删除字段 */
    async deleteField(field) {
      const tip = i18n.t('common.form.setting.deleteFieldTips2');
      if (!(await this.$platform.confirm(tip))) return;
      
      let index = this.value.indexOf(field)
      
      if (index >= 0) {
        // 如果是选中的字段，清除选中
        if (this.currField == field) this.formDesignComponent.currField = null;
        
        this.value.splice(index, 1);
      }
      
      this.emitInput(this.value);
    },
    /** 隐藏字段 */
    async hiddenField(item) {
      let tip = item.isSystem == 0 ? i18n.t('common.form.tip.hideFieldTips1') : i18n.t('common.form.tip.hideFieldTips2')
      if (!(await this.$platform.confirm(tip))) return;

      let index = this.value.indexOf(item);
      this.value[index].isHidden = 1;

      this.emitInput(this.value);
    },
    renderPersonalCenter(h) {
      return h(FormUserCenter.component.preview);
    },
    noticeFieldScrolling() {
      let noticePreviewComponents = findComponentsDownward(this, 'mform-text-preview')
      
      noticePreviewComponents.forEach(component => {
        component.$refs.NoticeBarComponent.reset()
        component.$refs.NoticeBarComponent.start()
      })
    },
    // 获取新版商城列表数据
    async getMallList() {
      try {
        const tenantId = useTenantId()?.value || '';
        const params = {
          pageNum: 0,
          pageSize: 10,
          keyWord: '',
          tenantId,
          type: 1,
        }
        const { code, data } = await commodityList(params);
        if (code !== '200') return;

        this.partList = data?.list || []
      } catch (error) {
        console.error('getMallList error', error);
      }
    },
    // 获取备件列表
    async getPartList() {
      try {
        const { code, data } = await queryPartList();
        if (code !== '200') return;

        this.partList = data?.list || []
      } catch (error) {
        console.error('getDoorTypeList error', error);
      }
    },
  },
  render(h) {
    // 是否左侧控件库拖拽，相同group之间可以相互拖拽，为阻止子表单和其他字段之间相互拖拽
    let group = 'widget'
    
    return (
      <draggable
        class={['form-preview', this.isEmpty && !this.isOnlyPreview && 'form-preview-empty']}
        animation="200"
        ghostClass="ghost"
        group="widget"
        list={this.value}
        filter=".disabled"
        onStart={() => {
          this.formDesignComponent.silence = true;
          if (this.isHasUserCenterField) {
            this.backupValue = cloneDeep(this.value)
          }
        }}
        onEnd={({ newIndex, oldIndex }) => {
          this.formDesignComponent.silence = false
          
          if (this.isHasUserCenterField && newIndex == 0) {
            this.formDesignComponent.emitInput(this.backupValue)
            this.formDesignComponent.currField = this.backupValue[oldIndex] || null
            return
          }
          
          let index = this.handlerIndexChanged(newIndex, oldIndex)
          this.formDesignComponent.currField = this.value[index] || null
          
          this.noticeFieldScrolling()
          
        }}
        onAdd={({ newIndex, oldIndex }) => {
          this.addEventHandler(newIndex, oldIndex)
        }}
      >
        {this.renderPreviewList(h)}
      </draggable>
    );
  },
  components: {
    ...PreviewComponents,
    draggable
  }
};

export default FormPreview;
